package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.util.ConverterUtils;
import com.alibaba.nacos.api.config.ConfigService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author tom
 */
public abstract class AbstractDynamicRuleProvider<T> implements DynamicRuleProvider<List<T>> {
    @Autowired
    private ConfigService configService;

    private Class<T> clazz;

    public AbstractDynamicRuleProvider(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public List<T> getRules(String appName) throws Exception {

        String rules = configService.getConfig(getDataId(appName), getGroup(appName), 3 * 1000);

        if (StringUtils.isEmpty(rules)) {
            return Lists.newArrayList();
        }

        return ConverterUtils.toListObject(rules, this.clazz);
    }

    protected abstract String getDataId(String appName);

    protected String getGroup(String appName) {
        return appName;
    }

}
